import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as bodyParser from 'body-parser';
import { TransformInterceptor } from './common/interceptor/transform.interceptor';
import { HttpStatus, ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { NestConfig, SwaggerConfig } from './config/config.interface';
import { ConfigService } from '@nestjs/config';
import { PrismaClientExceptionFilter } from 'nestjs-prisma';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import session from 'express-session';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 调大 body 大小限制，比如 50mb
  app.use(bodyParser.json({ limit: '100mb' }));
  app.use(bodyParser.urlencoded({ limit: '100mb', extended: true }));

  app.useGlobalInterceptors(new TransformInterceptor());
  app.setGlobalPrefix('api');
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      forbidUnknownValues: false,
      whitelist: true,
      transformOptions: {
        enableImplicitConversion: false,
      },
    }),
  );
  app.use(
    session({
      secret: 'hao3304',
      resave: false,
      saveUninitialized: false,
    }),
  );
  const configService = app.get(ConfigService);
  const swaggerConfig = configService.get<SwaggerConfig>('swagger');
  app.setGlobalPrefix('api');

  if (swaggerConfig?.enable) {
    const options = new DocumentBuilder()
      .setTitle(swaggerConfig.title)
      .setDescription(swaggerConfig.description)
      .setVersion(swaggerConfig.version)
      .addBearerAuth()
      .build();

    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup(swaggerConfig.path, app, document);
  }

  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(
    new PrismaClientExceptionFilter(httpAdapter, {
      P2000: HttpStatus.BAD_REQUEST,
      P2003: HttpStatus.BAD_REQUEST,
      P2022: HttpStatus.SERVICE_UNAVAILABLE,
      P2002: HttpStatus.CONFLICT,
      P2025: HttpStatus.NOT_FOUND,
    }),
  );

  app.useGlobalFilters(new HttpExceptionFilter());

  const nestConfig = configService.get<NestConfig>('nest');
  await app.listen(nestConfig!.port);

  return nestConfig!.port;
}
bootstrap().then((port) => console.log('服务启动成功: ' + port));
